package com.siki.salessystemoauth2server.controller;


import com.alibaba.fastjson.JSONObject;
import com.siki.salessystemcommon.entity.enumeration.GlobalServiceMsgCode;
import com.siki.salessystemcommon.utils.SystemMsgJsonResponse;
import com.siki.salessystemoauth2server.dto.RegisteredAccountDTO;
import com.siki.salessystemoauth2server.service.AccountService;
import com.siki.salessystemoauth2server.util.WebUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author Siki
 * @date 2020/12/27
 */
@RestController
@Api(tags = "[账号相关操作模块[注册/删除]]")
@RequestMapping("/account")
public class AccountController {
    private AccountService accountService;
    public final String VERIFICATION_USER_URL = "http://gmw.dgut.edu.cn/api/center/public/index.php/index/index/checkLogin";

    public AccountController(AccountService accountService) {
        this.accountService = accountService;
    }

    @PostMapping(value = "/registered")
    public SystemMsgJsonResponse registered(@RequestBody @Validated RegisteredAccountDTO dto) throws Exception {
        accountService.registered(dto);
        return SystemMsgJsonResponse.success();
    }

    @PostMapping(value = "/get")
    public SystemMsgJsonResponse get(Authentication authentication){
        String name = authentication.getName();
        return SystemMsgJsonResponse.success(name);
    }

    @PostMapping(value = "/delete/{id}")
    public SystemMsgJsonResponse deleteAccount(@PathVariable("id") @NotNull(message = "账号id不能为空") String id) {
        accountService.deleteAccount(id);
        return SystemMsgJsonResponse.success();
    }

    @PostMapping(value = "/returnInfo")
    public SystemMsgJsonResponse getUserInfo(@ApiParam("token") @RequestParam("token") String token) {
        JSONObject requestToken = new JSONObject();
        requestToken.put("token", token);
        JSONObject httpResponseResultJson = WebUtils.sendPostWithJson(VERIFICATION_USER_URL, requestToken);
        assert httpResponseResultJson != null;
        Integer errorCode = (Integer) httpResponseResultJson.get("error_code");
        //如果验证结果正常,不会有error_code;
        if (null == errorCode) {
            System.out.println(LocalDateTime.now().
                    format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " : " + httpResponseResultJson);
            httpResponseResultJson.put("token", token);
            return SystemMsgJsonResponse.success(httpResponseResultJson);
        } else {
            return SystemMsgJsonResponse.fail(GlobalServiceMsgCode.USER_TOKEN_EXPIRED,httpResponseResultJson.get("msg").toString());
        }
    }
}
